from django.db import transaction
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from cart.models import CartModel
from cart.cartser import CartSerializer
from rest_framework.generics import ListAPIView
from utils.authorization import MyAuthorization
from user.models import UserModel
from order.models import UserCoupon,CouponModel
from order import orderser

# Create your views here.
class CartView(ListAPIView):
    queryset = CartModel.objects.all()
    serializer_class = CartSerializer
    authentication_classes = [MyAuthorization, ]
    def get_queryset(self):
        user = self.request.query_params.get('user')
        if user:
            return self.queryset.filter(user=user,select=True)
class CouponView(APIView):
    authentication_classes = [MyAuthorization,]
    def get(self,request):
        user = request.query_params.get('user')
        userinfo = UserModel.objects.get(id=user)
        mycoupon = UserCoupon.objects.filter(user=user)
        ser = orderser.UserCouponSerialzer(instance=mycoupon,many=True)
        return Response({"massage":"success",'code':200,"data":{"credit":userinfo.credit,"tomoney":10,"coupon":ser.data}})

from utils.myredis import redistoll
 # 生成订单号
import random
import time
def get_order_num():
    order_num ="JD" + str(time.strftime('%Y%m%d%H%M%S')) + str(random.randint(1000,9999))
    return order_num

 # 生成订单
class Order(APIView):
    authentication_classes = [MyAuthorization, ]
    def post(self,request):
        user = request.data.get('user')
        order = redistoll.getstr(user)
        if order:
            return Response({"massage":"订单已存在，请勿重复提交",'code':200})
        # 开启事务的保存点
        transac = transaction.savepoint()
        try:
            # 1 订单号
            orderdata={
                'orderno':get_order_num(),
                'user':user,
                'score':request.data.get('score',0),
                'coupon':request.data.get('coupon',None),
                'paytype':request.data.get('paytype',1)
            }
            # 总价 去购物车拿当前用户选中的数据 做一个累加
            cart = CartModel.objects.filter(user_id=user,select=True)
            total = 0
            for i in cart:
                total += i.course.disc
            orderdata['totalprice'] = total
            orderdata['payprice'] = total
            # 计算实际支付的价格
            if orderdata['score']!=0:
                orderdata['payprice']=float(orderdata['totalprice']) - orderdata['score']/10
            if orderdata['coupon']!=None:
                cou=UserCoupon.objects.filter(id=orderdata['coupon']).first()
                if cou.isshow:
                    orderdata['payprice'] =orderdata['totalprice'] -cou.coupon.price
            print(orderdata)
            ordser = orderser.OrderSerializer(data=orderdata)
            if ordser.is_valid():
                ordser.save()
                for i in cart:
                    detail = {
                        'order':ordser.data.get('id'),
                        'course':i.course.id,
                        'price':i.course.price,
                        'discount':i.course.disc,
                        'ccover':"http://127.0.0.1:8000/uploads/"+str(i.course.cimg),
                        'cname':i.course.kname
                    }
                    detailser=orderser.OrderDetialSerializer(data=detail)
                    if detailser.is_valid():
                        detailser.save()
                    else:
                        return Response({"massage":detailser.errors,'code':400})
                    i.delete()
            else:
                return Response({"massage":ordser.errors,'code':400})
            redistoll.delstr(user)
            transaction.savepoint_commit(transac)
            return Response({"massage":"订单生成成功",'orderno':orderdata['orderno']})
        except:
            transaction.savepoint_rollback(transac)
            return Response({"massage":'订单生成失败'})






































































































